package com.zh.mediaservice.AiBigModel;

import okhttp3.*;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

@Component
public class DeepSeek {
    private String url = "http://zhz.nat100.top/api/chat";
//    @Async
    public  String getAnswer(String question) {
        // 构建请求体
        JSONObject requestBody = new JSONObject();
        requestBody.put("model", "deepseek-r1:1.5b");
        requestBody.put("stream", false);
        // 构建 messages 数组
        JSONArray messages = new JSONArray();
        messages.put(new JSONObject().put("role", "system").put("content", "你是一个医疗机器人，只能回答医疗相关问题，对于非医疗问题，请回答:抱歉,我只能回答医疗问题。"));
        messages.put(new JSONObject().put("role", "user").put("content", question));
        requestBody.put("messages", messages);
        // 构建 options 对象
        JSONObject options = new JSONObject();
        options.put("temperature", 0);
//        options.put("max_tokens", 500);
        requestBody.put("options", options);
        // 创建 OkHttp 客户端
        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(5, TimeUnit.MINUTES) // 连接超时
                .readTimeout(5, TimeUnit.MINUTES)   // 读取超时
                .writeTimeout(5, TimeUnit.MINUTES)  // 写入超时
                .build();;
        // 创建请求体
        RequestBody body = RequestBody.create(requestBody.toString(), MediaType.parse("application/json"));
        // 创建请求
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();
        // 发送请求并处理响应
        try (Response response = client.newCall(request).execute()) {
            if (response.isSuccessful() && response.body() != null) {
                String responseBody = response.body().string();
//                System.out.println("Response: " + responseBody);
                JSONObject jsonResponse = new JSONObject(responseBody);
                JSONObject message = jsonResponse.getJSONObject("message");
                String content = message.getString("content");
                System.out.println("content: " + content);
                String[] split = content.split("think");
                String[] split1 = split[2].split(">");
                return split1[1].replaceFirst("^[\\r\\n]+", "").replace("\n", "<br>");

            } else {
                System.out.println("Request failed with code: " + response.code());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
       return "抱歉,服务器错误,请稍后在试^_^";
    }
}
